package com.finance.system.configure.mvc;

import com.finance.system.support.bean.GlobalResponse;
import com.finance.system.support.exception.FinanceBusinessException;
import com.google.common.base.Throwables;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice(annotations = RestController.class)
public class ResponseBodyConverter implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        String name = methodParameter.getParameterType().getName();
        return !StringUtils.equals(name,GlobalResponse.class.getName());
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        String returnType = methodParameter.getParameterType().getName();
        if("void".equals(returnType)){
            return GlobalResponse.success(o);
        }
        if(!mediaType.includes(MediaType.APPLICATION_JSON)){
            return o;
        }
        if(o instanceof GlobalResponse){
            return o;
        }
        return GlobalResponse.success(o);
    }

    /**
     * 处理指定异常
     * @return
     */
    @ResponseBody
    @ExceptionHandler(FinanceBusinessException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public GlobalResponse handleException(FinanceBusinessException exception){
        return GlobalResponse.fail(exception.getErrorMsg(),exception.getErrorCode());
    }

    /**
     * 处理指定异常
     * @return
     */
    @ResponseBody
    @ExceptionHandler(AuthenticationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public GlobalResponse handleException(AuthenticationException exception){
        return GlobalResponse.fail(exception.getMessage(),null);
    }

    /**
     * 处理指定异常
     * @return
     */
    @ResponseBody
    @ExceptionHandler(Throwable.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public GlobalResponse handleException(Throwable exception){
        return GlobalResponse.fail(Throwables.getStackTraceAsString(exception),null);
    }
}
